﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;
using PTUDW_CNTN2010_F_CDT.Models;

namespace PTUDW_CNTN2010_F_CDT.Controllers
{
    public class AdminAdController : Controller
    {
        EcommerceDBContext db = new EcommerceDBContext();

        public ActionResult ViewAds()
        {
            return View();
        }

        public JsonResult GetListAds(int? page, int? rows, string sidx, string sord)
        {
            var assets = from a in db.Ads
                         orderby a.AdId
                         select new
                         {
                             ID = a.AdId,
                             Image = a.img,
                             URL = a.url,
                             Left = a.left
                         };

            //var sortedAssets = assets.SortBy(sidx, sord.Contains("DESC"));
            var pagedAssets = assets.ToPagedList(page ?? 1, rows ?? 20);

            var results = new
            {
                total = pagedAssets.PageCount,
                page = pagedAssets.PageNumber,
                records = assets.Count(),
                rows = pagedAssets
            };

            return Json(results);
        }

        public void Delete(int ID)
        {
            var cus = db.Ads.Find(ID);
            db.Ads.Remove(cus);
            db.SaveChanges();
        }

        [HttpPost]
        public void SaveChange(int ID, string Image, string URL, string Left)
        {
            var ad = db.Ads.Find(ID);
            if (ad == null)
            {
                ad = new Ad();
                db.Ads.Add(ad);
            }

            ad.img = Image;
            ad.url = URL;
            ad.left = (Left == "false");
            db.SaveChanges();
        }
    }
}
